﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Workflow.Runtime;
using System.Workflow.ComponentModel;
using Openfree.Workflow.Common;
using Openfree.Workflow.Activities;

public partial class Controls_Activity_QingJia : WorkflowUserControl
{

    protected void Page_Load(object sender, EventArgs e)
    {
        ProcessRole1.OnProcessedSelectRole += On_ProcessedSelectRole;
        ProcessRole1.OnCancelSelectRole += On_CancelSelectRole;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        Save(false);
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Save(true);
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        if (OnCancel != null) OnCancel(null, null);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="isSubmit">决定是否选择相应审批人</param>
    private void Save(Boolean isSubmit)
    {

        if (string.IsNullOrEmpty(tbSjDay.Text.Trim())) tbSjDay.Text = "0";
        if (string.IsNullOrEmpty(tbBjDay.Text.Trim())) tbBjDay.Text = "0";
        if (string.IsNullOrEmpty(tbNjDay.Text.Trim())) tbNjDay.Text = "0";
        if (string.IsNullOrEmpty(tbQtjDay.Text.Trim())) tbQtjDay.Text = "0";
        if (string.IsNullOrEmpty(tbJbdxDay.Text.Trim())) tbJbdxDay.Text = "0";
        if (string.IsNullOrEmpty(tbZbdxDay.Text.Trim())) tbZbdxDay.Text = "0";

        string processActivity = string.Empty;
        string instanceID = string.Empty;
        if (ViewState["_instanceID"] == null)
        {
            //add
            instanceID = WorkflowManager.AddWorkflow(typeof(QingJia), isSubmit, ddlSelectRole.SelectedValue);
            System.Threading.Thread.Sleep(800);
            //AddWorkflow 之后需要有一定延迟，才能获取最新状态
            processActivity = WorkflowManager.GetActivityState(new Guid(instanceID));

            DataSet ds = BaseAccess.GetDataSet(base.Connection, "select * from T_Workflow where 1=2", "T_Workflow");
            BaseAccess.FillDataSet(base.Connection, ds, "select * from WF_QingJia where 1=2", "WF_QingJia");

            DataRow rowWorkflow = ds.Tables["T_Workflow"].NewRow();
            rowWorkflow["InstanceID"] = instanceID;
            rowWorkflow["Subject"] = tbSubject.Text.Trim();
            rowWorkflow["CategoryCode"] = ViewState["CategoryCode"].ToString();
            rowWorkflow["UserID"] = SessionManager.UserID;
            rowWorkflow["CreateDate"] = DateTime.Now;
            rowWorkflow["StartDate"] = DateTime.Now;
            rowWorkflow["CurrentState"] = WorkflowStatus.Running;
            rowWorkflow["IsSubmit"] = 0;
            rowWorkflow["ProcessActivity"] = processActivity;
            ds.Tables["T_Workflow"].Rows.Add(rowWorkflow);

            DataRow rowQJ = ds.Tables["WF_QingJia"].NewRow();
            rowQJ["InstanceID"] = instanceID;
            rowQJ["UserID"] = SessionManager.UserID;
            rowQJ["BeginDate"] = tbBeginDate.Text.Trim() + " " + ddlBeginHH.SelectedValue + ":" + ddlBeginMM.SelectedValue;
            rowQJ["SjDay"] = tbSjDay.Text.Trim();
            rowQJ["BjDay"] = tbBjDay.Text.Trim();
            rowQJ["NjDay"] = tbNjDay.Text.Trim();
            rowQJ["QtjDay"] = tbQtjDay.Text.Trim();
            rowQJ["JbdxDay"] = tbJbdxDay.Text.Trim();
            rowQJ["ZbdxDay"] = tbZbdxDay.Text.Trim();
            rowQJ["Leaved"] = rbListLeaved.SelectedValue;
            rowQJ["WhereTo"] = tbWhereTo.Text.Trim();
            rowQJ["IsCar"] = cbIsCar.Checked;
            rowQJ["IsTrain"] = cbIsTrain.Checked;
            rowQJ["IsShip"] = cbIsShip.Checked;
            rowQJ["IsAircraft"] = cbIsAircraft.Checked;
            if (string.IsNullOrEmpty(tbLeaveDate.Text.Trim()))
            {
                rowQJ["LeaveDate"] = DBNull.Value;
            }
            else
            {
                rowQJ["LeaveDate"] = tbLeaveDate.Text.Trim() + " " + ddlLeaveHH.SelectedValue + ":" + ddlLeaveMM.SelectedValue;

            }
            if (string.IsNullOrEmpty(tbBackDate.Text.Trim()))
            {
                rowQJ["BackDate"] = DBNull.Value;
            }
            else
            {
                rowQJ["BackDate"] = tbBackDate.Text.Trim() + " " + ddlBackHH.SelectedValue + ":" + ddlBackMM.SelectedValue;
            }
            rowQJ["Description"] = tbDescription.Text.Trim();
            ds.Tables["WF_QingJia"].Rows.Add(rowQJ);

            BaseAccess.UpdateDataSet(base.Connection, new string[] { "T_Workflow", "WF_QingJia" }, ds);
        }
        else
        {
            //edit
            instanceID = ViewState["_instanceID"].ToString();
            DataSet ds = BaseAccess.GetDataSet(base.Connection,
                string.Format("select * from T_Workflow where InstanceID='{0}'", instanceID), "T_Workflow");
            BaseAccess.FillDataSet(base.Connection, ds,
                string.Format("select * from WF_QingJia where InstanceID='{0}'", instanceID), "WF_QingJia");

            DataRow rowWorkflow = ds.Tables["T_Workflow"].Rows[0];
            rowWorkflow["Subject"] = tbSubject.Text.Trim();
            rowWorkflow["StartDate"] = DateTime.Now;
            rowWorkflow["CurrentState"] = WorkflowStatus.Running;

            processActivity = WorkflowManager.GetActivityState(new Guid(instanceID));
            if (isSubmit && processActivity == "InitialState")
            {
                //ascx所在的页面不同，入口不一样，所以Edit时需要判断一下当前的ActivityState
                WorkflowManager.RaiseApproveEvent(new Guid(instanceID), null);
                //AddWorkflow 之后需要有一定延迟，才能获取最新状态
                System.Threading.Thread.Sleep(500);
                rowWorkflow["ProcessActivity"] = WorkflowManager.GetActivityState(new Guid(instanceID));
            }


            DataRow rowQJ = ds.Tables["WF_QingJia"].Rows[0];
            rowQJ["BeginDate"] = tbBeginDate.Text.Trim() + " " + ddlBeginHH.SelectedValue + ":" + ddlBeginMM.SelectedValue;
            rowQJ["SjDay"] = tbSjDay.Text.Trim();
            rowQJ["BjDay"] = tbBjDay.Text.Trim();
            rowQJ["NjDay"] = tbNjDay.Text.Trim();
            rowQJ["QtjDay"] = tbQtjDay.Text.Trim();
            rowQJ["JbdxDay"] = tbJbdxDay.Text.Trim();
            rowQJ["ZbdxDay"] = tbZbdxDay.Text.Trim();
            rowQJ["Leaved"] = rbListLeaved.SelectedValue;
            rowQJ["WhereTo"] = tbWhereTo.Text.Trim();
            rowQJ["IsCar"] = cbIsCar.Checked;
            rowQJ["IsTrain"] = cbIsTrain.Checked;
            rowQJ["IsShip"] = cbIsShip.Checked;
            rowQJ["IsAircraft"] = cbIsAircraft.Checked;
            if (string.IsNullOrEmpty(tbLeaveDate.Text.Trim()))
            {
                rowQJ["LeaveDate"] = DBNull.Value;
            }
            else
            {
                rowQJ["LeaveDate"] = tbLeaveDate.Text.Trim() + " " + ddlLeaveHH.SelectedValue + ":" + ddlLeaveMM.SelectedValue;

            }
            if (string.IsNullOrEmpty(tbBackDate.Text.Trim()))
            {
                rowQJ["BackDate"] = DBNull.Value;
            }
            else
            {
                rowQJ["BackDate"] = tbBackDate.Text.Trim() + " " + ddlBackHH.SelectedValue + ":" + ddlBackMM.SelectedValue;
            }
            rowQJ["Description"] = tbDescription.Text.Trim();


            BaseAccess.UpdateDataSet(base.Connection, new string[] { "T_Workflow", "WF_QingJia" }, ds);
        }

        if (isSubmit)
        {
            pnlEdit.Visible = false;
            pnlRole.Visible = true;
            ProcessRole1.InitData(instanceID, processActivity);
        }
        else
        {
            if (OnSave != null) OnSave(null, null);
        }
        ClearValue();
    }

    protected virtual void On_ProcessedSelectRole(object sender, EventArgs e)
    {
        pnlEdit.Visible = true;
        pnlRole.Visible = false;
        if (OnSubmit != null) OnSubmit(null, null);
    }

    protected virtual void On_CancelSelectRole(object sender, EventArgs e)
    {
        pnlEdit.Visible = true;
        pnlRole.Visible = false;
        if (OnSave != null) OnSave(null, null);
    }

    private void ClearValue()
    {
        tbSubject.Text = "";
        tbBeginDate.Text = "";
        tbSjDay.Text = "";
        tbBjDay.Text = "";
        tbNjDay.Text = "";
        tbQtjDay.Text = "";
        tbJbdxDay.Text = "";
        tbZbdxDay.Text = "";
        rbListLeaved.SelectByValue = "0";
        tbWhereTo.Text = "";
        cbIsCar.Checked = false;
        cbIsTrain.Checked = false;
        cbIsShip.Checked = false;
        cbIsAircraft.Checked = false;
        tbLeaveDate.Text = "";
        ddlLeaveHH.SelectedIndex = 0;
        ddlLeaveMM.SelectedIndex = 0;
        tbBackDate.Text = string.Empty;
        ddlBackHH.SelectedIndex = 0;
        ddlBackMM.SelectedIndex = 0;
        tbDescription.Text = "";
    }

    public override void InitDate()
    {
        base.InitDate();


        literalSubject.Text = ViewState["Subject"].ToString();

        ddlBeginHH.Items.Clear();
        ddlLeaveHH.Items.Clear();
        ddlBackHH.Items.Clear();
        for (int i = 0; i < 24; i++)
        {
            ddlBeginHH.Items.Add(new ListItem(i.ToString() + "时", i.ToString("00")));
            ddlLeaveHH.Items.Add(new ListItem(i.ToString() + "时", i.ToString("00")));
            ddlBackHH.Items.Add(new ListItem(i.ToString() + "时", i.ToString("00")));

        }
        ddlBeginMM.Items.Clear();
        ddlLeaveMM.Items.Clear();
        ddlBackMM.Items.Clear();
        for (int i = 0; i < 60; i++)
        {
            ddlBeginMM.Items.Add(new ListItem(i.ToString() + "分", i.ToString("00")));
            ddlLeaveMM.Items.Add(new ListItem(i.ToString() + "分", i.ToString("00")));
            ddlBackMM.Items.Add(new ListItem(i.ToString() + "分", i.ToString("00")));
        }

        ddlSelectRole.Items.Clear();
        SecurityAccess securityAccess = new SecurityAccess(base.Connection);
        DataSet ds = securityAccess.LoadPermission(SessionManager.UserID);
        if (ds.Tables[0].Rows.Count > 0)
        {
            foreach (DataRow row in ds.Tables[0].Select("Category='审批角色'", "OrderIndex desc"))
            {
                ListItem item = new ListItem();
                item.Text = row["Subject"].ToString();
                item.Value = row["Description"].ToString();
                ddlSelectRole.Items.Add(item);
            }
        }
        else
        {
            trSelectRole.Visible = false;
        }
        ddlSelectRole.Items.Insert(0, new ListItem("普通员工", ""));
    }

    public override void InitViewData(string instanceID, DataRow rowWorkflow, Boolean processVisibled)
    {
        base.InitViewData(instanceID, rowWorkflow, processVisibled);
        pnlEdit.Visible = false;
        pnlView.Visible = true;
        divCancelButton.Visible = true;
        trSelectRole.Visible = false;
        lbLeaveDate.Text = string.Empty;
        lbBackDate.Text = string.Empty;


        string cmdText = "select * from WF_QingJia where InstanceID='{0}'";
        cmdText = string.Format(cmdText, instanceID);
        DataSet ds = BaseAccess.GetDataSet(base.Connection, cmdText);
        DataRow row = ds.Tables[0].Rows[0];

        literalSubject2.Text = ViewState["Subject"].ToString();

        lbSubject.Text = HttpUtility.HtmlEncode(rowWorkflow["Subject"].ToString());
        lbBeginDate.Text = Convert.ToDateTime(row["BeginDate"].ToString()).ToString("yyyy-MM-dd HH:mm");
        lbSjDay.Text = row["SjDay"].ToString();
        lbBjDay.Text = row["BjDay"].ToString();
        lbNjDay.Text = row["NjDay"].ToString();
        lbQtjDay.Text = row["QtjDay"].ToString();
        lbJbdxDay.Text = row["JbdxDay"].ToString();
        lbZbdxDay.Text = row["ZbdxDay"].ToString();
        rbListLeaved2.SelectByValue = row["Leaved"].ToString();
        lbWhereTo.Text = row["WhereTo"].ToString();
        cbIsCar2.Value = row["IsCar"].ToString();
        cbIsTrain2.Value = row["IsTrain"].ToString();
        cbIsShip2.Value = row["IsShip"].ToString();
        cbIsAircraft2.Value = row["IsAircraft"].ToString();
        if (!Convert.IsDBNull(row["LeaveDate"]))
        {
            lbLeaveDate.Text = Convert.ToDateTime(row["LeaveDate"].ToString()).ToString("yyyy-MM-dd HH:mm");
        }
        if (!Convert.IsDBNull(row["BackDate"]))
        {
            lbBackDate.Text = Convert.ToDateTime(row["BackDate"].ToString()).ToString("yyyy-MM-dd  HH:mm");
        }
        lbDescription.Text = HttpUtility.HtmlEncode(row["Description"].ToString()).Replace("\r\n", "<br />"); ;

        bool flag = ProcessList1.InitProcess(instanceID, processVisibled);
        ProcessList1.OnProcessed += base.On_Processed;
        ProcessList1.OnCancel += base.On_Cancel;

        divCancelButton.Visible = !flag;
    }



    public override void InitEditData(string instanceID, DataRow rowWorkflow, Boolean processVisibled)
    {
        ViewState["_instanceID"] = instanceID;
        base.InitEditData(instanceID, rowWorkflow, processVisibled);
        pnlEdit.Visible = true;
        pnlView.Visible = false;
        divCancelButton.Visible = false;
        trSelectRole.Visible = false;
        InitDate();

        tbLeaveDate.Text = string.Empty;
        ddlLeaveHH.SelectedIndex = 0;
        ddlLeaveMM.SelectedIndex = 0;
        tbBackDate.Text = string.Empty;
        ddlBackHH.SelectedIndex = 0;
        ddlBackMM.SelectedIndex = 0;


        string cmdText = "select * from WF_QingJia where InstanceID='{0}'";
        cmdText = string.Format(cmdText, instanceID);
        DataSet ds = BaseAccess.GetDataSet(base.Connection, cmdText);
        DataRow rowQJ = ds.Tables[0].Rows[0];

        //literalSubject2.Text = ViewState["Subject"].ToString();
        tbSubject.Text = rowWorkflow["Subject"].ToString();
        tbBeginDate.Text = Convert.ToDateTime(rowQJ["BeginDate"].ToString()).ToString("yyyy-MM-dd");
        ddlBeginHH.SelectByValue = Convert.ToDateTime(rowQJ["BeginDate"].ToString()).ToString("HH");
        ddlBeginMM.SelectByValue = Convert.ToDateTime(rowQJ["BeginDate"].ToString()).ToString("mm");
        tbSjDay.Text = rowQJ["SjDay"].ToString();
        tbBjDay.Text = rowQJ["BjDay"].ToString();
        tbNjDay.Text = rowQJ["NjDay"].ToString();
        tbQtjDay.Text = rowQJ["QtjDay"].ToString();
        tbJbdxDay.Text = rowQJ["JbdxDay"].ToString();
        tbZbdxDay.Text = rowQJ["ZbdxDay"].ToString();
        rbListLeaved.SelectByValue = rowQJ["Leaved"].ToString();
        tbWhereTo.Text = rowQJ["WhereTo"].ToString();
        cbIsCar.Value = rowQJ["IsCar"].ToString();
        cbIsTrain.Value = rowQJ["IsTrain"].ToString();
        cbIsShip.Value = rowQJ["IsShip"].ToString();
        cbIsAircraft.Value = rowQJ["IsAircraft"].ToString();
        if (!Convert.IsDBNull(rowQJ["LeaveDate"]))
        {
            tbLeaveDate.Text = Convert.ToDateTime(rowQJ["LeaveDate"].ToString()).ToString("yyyy-MM-dd");
            ddlLeaveHH.SelectByValue = Convert.ToDateTime(rowQJ["LeaveDate"].ToString()).ToString("HH");
            ddlLeaveMM.SelectByValue = Convert.ToDateTime(rowQJ["LeaveDate"].ToString()).ToString("mm");
        }
        if (!Convert.IsDBNull(rowQJ["BackDate"]))
        {
            tbBackDate.Text = Convert.ToDateTime(rowQJ["BackDate"].ToString()).ToString("yyyy-MM-dd");
            ddlBackHH.SelectByValue = Convert.ToDateTime(rowQJ["BackDate"].ToString()).ToString("HH");
            ddlBackMM.SelectByValue = Convert.ToDateTime(rowQJ["BackDate"].ToString()).ToString("mm");
        }
        tbDescription.Text = rowQJ["Description"].ToString();

        ProcessList1.InitProcess(instanceID, processVisibled);
        ProcessList1.OnProcessed += base.On_Processed;
        ProcessList1.OnCancel += base.On_Cancel;
    }
}
